import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import request, { axiosInstance } from '../utils/request';
import { login as apiLogin, getAuthMenu as apiGetAuthMenu } from '../api/auth';

// 菜单数据类型定义
export interface MenuItemType {
    id: number;
    name: string;
    path: string;
    component: string;
    icon?: string;
    showInMenu: number;
    children?: MenuItemType[];
}

// 用户信息类型
export interface UserInfoType {
    id: number;
    username: string;
    role: string;
    avatar?: string;
}

interface AuthState {
    token: string | null;
    userInfo: UserInfoType | null;
    authMenus: MenuItemType[]; // 权限菜单列表（后台返回）
    isLoading: boolean; // 权限加载中状态

    // 登录：获取token、用户信息、权限菜单
    login: (username: string, password: string) => Promise<void>;
    // 退出登录：清空状态
    logout: () => void;
    // 刷新权限（如页面刷新时）
    refreshAuth: () => Promise<void>;
    initAuth: () => void;
}

export const useAuthStore = create<AuthState>()(
    persist(
        (set, get) => ({
            token: null,
            userInfo: null,
            authMenus: [],
            isLoading: false,

            login: async (username, password) => {
                try {
                    // 1. 调用登录接口（拦截器会自动处理非200状态码）
                    const loginData = await apiLogin({ username, password });
                    console.log('loginData::', loginData);
                    const { token, user } = loginData;
                    localStorage.setItem('auth_token', token)
                    localStorage.setItem('user_info', JSON.stringify(user))
                    set({
                        token,
                        userInfo: user,
                    });
                    const authAxiosRes = await apiGetAuthMenu();
                    localStorage.setItem('authMenus', JSON.stringify(authAxiosRes))
                    set({
                        authMenus: authAxiosRes,
                        isLoading: false,
                    });

                } catch (error) {
                    console.error('登录失败:', error);
                    set({ isLoading: false });
                    throw error;
                }
            },

            logout: () => {
                delete axiosInstance.defaults.headers.common['Authorization'];
                set({
                    token: null,
                    userInfo: null,
                    authMenus: [],
                });
                window.location.href = '/login';
            },

            refreshAuth: async () => {
                // 暂未启用
            },

            initAuth: () => {
                const token = localStorage.getItem('auth_token');
                const userInfo = localStorage.getItem('user_info');
                const menusStr = localStorage.getItem('authMenus');
                if (token && menusStr && userInfo) {
                    try {
                        const menus = JSON.parse(menusStr) as MenuItemType[];
                        set({ token, userInfo: JSON.parse(userInfo) as UserInfoType, authMenus: menus });
                    } catch (e) {
                        console.error('解析菜单失败', e);
                    }
                }
            },
        }),
        {
            name: 'auth-storage',
            partialize: (state) => ({ token: state.token }),
        }
    )
);